#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdint.h>
#include <errno.h>

#include "mytbf.h"

#define CPS		100
#define BURST	200

#define BUFSIZE 1024

int
main(int argc, char **argv)
{
	int sfd, dfd;
	char buf[BUFSIZE];
	int pos, len, ret, tok;
	mytbf_ctx_t *ctx;

	if (argc<2) {
		fprintf(stderr, "Usage...\n");
		exit(1);
	}

	ctx = mytbf_ctx_init(CPS, BURST);
	if (ctx==NULL) {
		perror("mytbf_ctx_init()");
		exit(1);
	}

	sfd = open(argv[1], O_RDONLY);
	if (sfd<0) {
		perror("open(src)");
		exit(1);
	}

	dfd = 1;

	while (1) {
		len = read(sfd, buf, BUFSIZE);
		if (len<0) {
			if (errno==EINTR) {
				continue;
			}
			perror("read()");
			exit(1);
		}
		if (len==0) {
			break;
		}
		pos=0;
		while (len>0) {
			ret = write(dfd, buf+pos, mytbf_request(ctx, len));
			if (ret<0) {
				if (errno==EINTR) {
					continue;
				}
				perror("write()");
				exit(1);
			}
			pos += ret;
			len -= ret;
		}
	}

	close(sfd);

	mytbf_ctx_destroy(ctx);

	return 0;
}

